package com.joshua.ticket.manager.interceptor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.joshua.ticket.utils.MenuCache;
import com.joshua.userservice.models.Menu;
import com.joshua.userservice.models.User;

public class AuthenticateInterceptor implements HandlerInterceptor,
		ServletContextAware {

	@Autowired
	public SessionFactory sessionFactory;

	@Autowired
	public ServletContext httpApplication;

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		String accessUrl = request.getRequestURI();
		if (this.httpApplication.getAttribute("menus") == null) {
			initMenusCache();
			printAllMenus();
		}
		if (accessUrl.equals("/ticket-manager/login.do")
				|| accessUrl.equals("/ticket-manager/loginPage.do")) {
			return true;
		}
		if (session != null && session.getAttribute("LOGIN_USER") != null) {
			if (CheckPemissions(accessUrl, session)) {

				return true;
			} else {
				return false;
			}

		} else {
			response.sendRedirect("/ticket-manager/loginPage.do");
			return false;

		}

	}

	private void printAllMenus() {
		Menu root = (Menu) this.httpApplication.getAttribute("rootMenu");
		printChildMenu(root);

	}

	private void printChildMenu(Menu root) {
		System.out.println(root.getCode());
		System.out.println(root.getDisplayName());
		for (Menu menu : root.getChildrenMenus()) {
			printChildMenu(menu);
		}

	}

	private boolean CheckPemissions(String accessUrl, HttpSession session) {
		return true;
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

	public void setServletContext(ServletContext servletContext) {
		this.httpApplication = servletContext;
	}

	private void initMenusCache() {
		Menu root = null;
		try {
			Session session = sessionFactory.openSession();
			Transaction tx = session.beginTransaction();
			/*
			 * List menus = session.createQuery("from Menu").list();
			 * 
			 * for (Object oMenu : menus) { Menu menu = (Menu) oMenu;
			 * menuMap.put(menu.getCode(), menu); }
			 */
			List list = session.createCriteria(Menu.class)
					.add(Restrictions.eq("code", "root")).list();

			if (list.size() == 1) {
				root = (Menu) list.get(0);
				fetchChildren(root);
			}

			tx.commit();
			session.close();
			this.httpApplication.setAttribute("rootMenu", root);

		} catch (Exception ex) {
			System.out.println(ex.getMessage());
			System.out.println(ex.getCause().getMessage());
		}
	}

	private void fetchChildren(Menu root) {

		for (Menu menu : root.getChildrenMenus()) {
			menu.getCode();
			fetchChildren(menu);
		}

	}

}
